<template>
  <Card style="width:100%" class="detail-content-layout mb16">
    <template #title>
      {{ $t('最终验收') }}
    </template>
    <template #extra>
      <Icon @click="printPreviewPdf('FAT',info)" style="font-size: 19px; margin-right: 10px;" type="ios-print"/>
      <div class="h-arrow-wrap" @click="toggle = !toggle">
        <i :class="{toggleActive:toggle}" class="iconfont zy-common-jiantou h-arrow-icon"></i>
      </div>
    </template>
    <transition name="slide-up">
      <div v-if="toggle">
        <Form ref="form" :model="form" :rules="rules" label-position="top">
          <Row :gutter="24">
            <Col span="6">
              <FormItem :label="$t('分布情况')">
                <Input maxlength="200" :disabled="disabled" clearable type="text" v-model="form.distribution"
                       :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('FAT编号')" prop="atNo">
                <Input maxlength="200" :disabled="disabled" clearable type="text" v-model="form.atNo"
                       :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('KONE-合同号')">
                <Input disabled clearable type="text" v-model="form.contractNo"
                       :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('机器编号')">
                <Input maxlength="200" :disabled="disabled" clearable type="text" v-model="form.machineNo"
                       :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="24">
              <FormItem  :label="$t('机器或设备的描述')">
                <Input maxlength="200" :disabled="disabled" clearable type="textarea" rows="5" v-model="form.descriptionOfMe"
                       :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem  :label="$t('产品')">
                <Input maxlength="200" :disabled="disabled" clearable type="text" v-model="form.product"
                       :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('操作编号')">
                <Input maxlength="200" :disabled="disabled" clearable type="text" v-model="form.operationNo"
                       :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('FAT的日期')" prop="atTime" required>
                <DatePicker :disabled="disabled" v-model="form.atTime" type="date"
                            :placeholder="$t('请选择')"></DatePicker>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('KONE-参与者')" prop="participants">
                <Select
                    transfer
                    v-if="!disabled"
                    :disabled="disabled"
                    v-model="form.participants"
                    filterable
                    multiple
                    clearable
                    :remote-method="searchUserList"
                    :placeholder="`${$t('common.selectInfo')}`"
                >
                  <Option v-for="(item,index) in userList" :key="index" :value="item.id"
                          :label="item.realname"></Option>
                </Select>
                <Select
                    transfer
                    v-if="disabled"
                    v-model="form.participants"
                    multiple
                    disabled
                    :placeholder="`${$t('common.selectInfo')}`"
                >
                  <Option v-for="(item,index) in userNameList" :key="index" :value="item.id"
                          :label="item.realname"></Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('供应商-参与者')" prop="suppliersParticipants">
                <Input maxlength="200" :disabled="disabled" clearable type="text" v-model="form.suppliersParticipants"
                       :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('FAT结果')" prop="atResult">
                <Select
                    transfer
                    :disabled="disabled"
                    v-model="form.atResult"
                    filterable
                    clearable
                    :placeholder="`${$t('common.selectInfo')}`"
                    @on-change="changeAtResult"
                >
                  <Option v-for="(item,index) in fatResultList" :key="index" :value="item.label"
                          :label="item.label"/>
                </Select>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('以下是接受的细节')" prop="herewithAccepted" :required="form.atResult==='The machine or equipment is conditionally accepted by KONE'">
                <Select
                    transfer
                    :disabled="disabled||form.atResult!=='The machine or equipment is conditionally accepted by KONE'"
                    v-model="form.herewithAccepted"
                    filterable
                    clearable
                    :placeholder="`${$t('common.selectInfo')}`"
                    @on-change="changeHerewithAccepted"
                >
                  <Option v-for="(item,index) in herewithAcceptedDetailList" :key="index" :value="item.label"
                          :label="item.label"/>
                </Select>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('日期')" prop="fatDatetime" :required="checkHerewithAccepted()">
                <DatePicker ref="fatDatetime" :disabled="disabled ||!checkHerewithAccepted()"
                            v-model="form.fatDatetime" type="date"
                            :placeholder="$t('请选择')"></DatePicker>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('设备的功能和执行')" prop="functionExecution">
                <Select
                    transfer
                    :disabled="disabled"
                    v-model="form.functionExecution"
                    filterable
                    clearable
                    :placeholder="`${$t('common.selectInfo')}`"
                >
                  <Option v-for="(item,index) in resultList" :key="index" :value="item.label"
                          :label="item.label"/>
                </Select>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('电动、气动和液压')" prop="electriclHydraulic">
                <Select
                    transfer
                    :disabled="disabled"
                    v-model="form.electriclHydraulic"
                    filterable
                    clearable
                    :placeholder="`${$t('common.selectInfo')}`"
                >
                  <Option v-for="(item,index) in resultList" :key="index" :value="item.label"
                          :label="item.label"/>
                </Select>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('工艺质量或精度')"  prop="qualityAccuracy">
                <Select
                    transfer
                    :disabled="disabled"
                    v-model="form.qualityAccuracy"
                    filterable
                    clearable
                    :placeholder="`${$t('common.selectInfo')}`"
                >
                  <Option v-for="(item,index) in resultList" :key="index" :value="item.label"
                          :label="item.label"/>
                </Select>
              </FormItem>
            </Col>
            <Col span="6">
              <FormItem :label="$t('机器能力和利用率')" prop="machineUtilization">
                <Select
                    transfer
                    :disabled="disabled"
                    v-model="form.machineUtilization"
                    filterable
                    clearable
                    :placeholder="`${$t('common.selectInfo')}`"
                >
                  <Option v-for="(item,index) in resultList" :key="index" :value="item.label"
                          :label="item.label"/>
                </Select>
              </FormItem>
            </Col>

            <Col span="6">
              <FormItem :label="$t('提交人')" v-if="disabled">
                <Input disabled clearable type="text" v-model="form.submitByStr" :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
            <Col span="6" v-if="disabled">
              <FormItem :label="$t('提交时间')">
                <Input disabled clearable type="text" v-model="form.submitTime" :placeholder="$t('请输入')"></Input>
              </FormItem>
            </Col>
          </Row>
        </Form>
        <satTable type="FAT" ref="satTable" :disabled="disabled" :list="fatDetailDtos"/>
        <rejectInfo :rejectFlows="rejectFlows"/>
      </div>
    </transition>
  </Card>
</template>

<script>
// import uploadFile from "@/views/devBasic/capex/components/uploadFile";
import mixins from "@/views/devBasic/capex/components/mixins";
import rejectInfo from "@/views/devBasic/capex/components/rejectInfo";
import satTable from "@/views/devBasic/capex/components/satTable";
import moment from "moment";

export default {
  name: "FAT",
  components: {rejectInfo, satTable},
  mixins: [mixins],
  props: {
    info: {
      type: Object,
      default: () => {
      }
    },
    disabled: {
      type: Boolean,
      default: false
    },
    approvalInfo: {
      type: Object,
      default: () => {
      }
    },
    rejectFlows: {
      type: Object,
      default: () => {
      }
    },
    expand: {
      type: Boolean,
      default: false
    },
  },
  data() {
    const validateSelect = (rule, value, callback) => {
      if (!(Array.isArray(this.form.participants) && this.form.participants.length > 0)) {
        callback(new Error(this.$t('请选择')));
      } else {
        callback();
      }
    };
    const validateSelectDate = (rule, value, callback) => {
      console.log(value)
      if (!value || value ==null) {
        callback(new Error(this.$t('请选择')));
      } else {
        callback();
      }
    };

    const validateSelectHerewithAcceptedDate = (rule, value, callback) => {
      if (!this.form.fatDatetime  && this.checkHerewithAccepted()) {
        callback(new Error(this.$t('请选择')));
      } else {
        callback();
      }
    };
    const validateSelectHerewithAccepted = (rule, value, callback) => {
      if (!value  && this.form.atResult==='The machine or equipment is herewith accepted by KONE') {
        callback(new Error(this.$t('请选择')));
      } else {
        callback();
      }
    };
    return {
      toggle: true,
      userList: [],
      form: {
        atNo: "",
        atTime: "",
        participants: [],
        suppliersParticipants: "",
        atResult: "",
        herewithAccepted: null,
        fatDatetime: "",
        functionExecution:"",
        electriclHydraulic:"",
        qualityAccuracy:"",
        machineUtilization:""
      },
      rules: {
        // sats: [{ required:true,validator: validateFile, trigger: 'change'}],
        atNo: [{required: true, type: "string", message: this.$t('请输入'), trigger: 'blur'}],
        atTime: [{trigger: 'change', validator: validateSelectDate}],
        atResult: [{required: true, type: "string", message: this.$t('请输入'), trigger: 'change'}],
        participants: [{required: true, validator: validateSelect, trigger: 'change'}],
        suppliersParticipants: [{required: true, type: "string", message: this.$t('请输入'), trigger: 'change'}],
        herewithAccepted: [{trigger: 'change', validator: validateSelectHerewithAccepted}],
        functionExecution : [{required: true, type: "string", message: this.$t('请输入'), trigger: 'change'}],
        electriclHydraulic : [{required: true, type: "string", message: this.$t('请输入'), trigger: 'change'}],
        qualityAccuracy : [{required: true, type: "string", message: this.$t('请输入'), trigger: 'change'}],
        machineUtilization: [{required: true, type: "string", message: this.$t('请输入'), trigger: 'change'}],
        fatDatetime:[{trigger: 'change', validator: validateSelectHerewithAcceptedDate}],
      },
      fatDetailDtos: [],
      userNameList: []
    }
  },
  created() {
    this.form.submitByStr = this.userName
    const {fatDetailDtos, csoffContractNo, assetNo} = this.info;
    this.fatDetailDtos = fatDetailDtos
    this.form.contractNo = csoffContractNo
    this.form.machineNo = assetNo

    if (this.disabled) {
      // this.setParams()
      this.toggle = false
    }
    if (this.info.fatInfo && this.info.fatInfo.id){
      this.setParams()
    }else{
      const list = this.info.csDetails.filter(item => {
        if (item.processCode == 3) {
          item.status = 1
          item.edit = true
          item.result = 0
          item.indexCode = Math.random()
          item.who = this.userName
          item.isFirst = 1
          return item;
        }
      })

      this.fatDetailDtos = list;
    }
    // else if (this.rejectFlows && this.rejectFlows.approvalRemark) {
    //   this.setParams()
    //   this.toggle = true
    // }

    // if (!this.disabled && Object.keys(this.rejectFlows).length < 1) {
    //
    // }

    if (this.expand) {
      this.toggle = true
    }

    // this.disabled = false
  },
  methods: {
    checkHerewithAccepted(){
      return this.form.herewithAccepted==='全部技术方面的细节和结果可参见验收报告。日期为：'||this.form.herewithAccepted==='有一些小问题，供货商必须整改或更换零部件，在右述日期前：'
    },
    changeAtResult(e) {
      this.form.herewithAccepted = null
      delete this.form.fatDatetime
    },
    changeHerewithAccepted(e) {
      if (!this.checkHerewithAccepted()){
        delete this.form.fatDatetime
        // this.form.fatDatetime = ""
      }

    },
    setParams() {
      const {submitByStr, submitTime, submitRemark} = this.approvalInfo
      const {
        distribution,
        atNo,
        contractNo,
        machineNo,
        descriptionOfMe,
        product,
        operationNo,
        atTime,
        participants,
        suppliersParticipants,
        atResult,
        machineUtilization,
        qualityAccuracy,
        electriclHydraulic,
        functionExecution,
        herewithAccepted,
        fatDatetime,
        participantNames
      } = this.info.fatInfo || {};
      Object.assign(this.form, {
        remark: submitRemark,
        submitTime,
        submitByStr,
        distribution,
        atNo,
        contractNo,
        machineNo,
        descriptionOfMe,
        product,
        operationNo,
        atTime,
        participants: participants.split(','),
        suppliersParticipants,
        atResult,
        machineUtilization,
        qualityAccuracy,
        electriclHydraulic,
        functionExecution,
        herewithAccepted,
        fatDatetime
      })


      let _participantNames = participantNames.split(',');
      let _participants = participants.split(',')
      let userList = [];

      _participantNames.forEach((item, index) => {
        const id = _participants[index]
        userList.push({
          id: id / 1,
          realname: item
        })

        this.form.participants.push(id / 1)
      })


      if (!this.disabled)
        this.searchUserList("")
      else
        this.userNameList = JSON.parse(JSON.stringify(userList))

      this.$forceUpdate()

    },
    searchUserList(query) {
      this.axios({
        method: 'get',
        url: '/dms/user/userList',
        params: {key: query}
      }).then(res => {
        if (res.code === 200) {
          this.userList = res.data
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    async getParams(status) {
      const valid = status?status:await this.$refs.form.validate()
      const list = this.$refs.satTable.getParams()
      const params = JSON.parse(JSON.stringify(this.form))
      params.participants = (params.participants || []).join(',')
      params.atTime = params.atTime ? moment(params.atTime).format('YYYY-MM-DD'):""
      if (params.fatDatetime) {
        params.fatDatetime = params.fatDatetime ? moment(params.fatDatetime).format('YYYY-MM-DD'):""
      }else{
        delete params.fatDatetime
      }

      if (valid) {
          if (!status){
              if (list.find(item => item.edit)) {
                  this.$Message.error(this.$t('请先保存'))
                  return;
              }
              if (list.length < 1) {
                  this.$Message.error(this.$t('最少添加一条数据'))
                  return;
              }
          }

        return {
          scfInfoDto: {...params},
          scfDetailDtos: list
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import "./style";
</style>

